package com.tywj.panda.customer.common.widget.calendar

import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.SnapHelper

/**
 * <pre>
 *     author : June Yang
 *     time   : 2020/06/1
 *     desc   : 实现RecyclerView的OnPageChangeListener功能
 *     version: 2.0.0
 * </pre>
 */
open class RecyclerViewPageChangeListenerHelper(
    private val snapHelper: SnapHelper,

    private val onPageChangeListener: OnPageChangeListener?

) : RecyclerView.OnScrollListener() {

    //防止同一Position多次触发
    private var oldPosition = -1

    override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
        super.onScrolled(recyclerView, dx, dy)

        onPageChangeListener?.onScrolled(recyclerView, dx, dy)
    }

    override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
        super.onScrollStateChanged(recyclerView, newState)

        var position = 0
        val layoutManager = recyclerView.layoutManager
        //获取当前选中的itemView
        val view = snapHelper.findSnapView(layoutManager)

        view?.let {
            //获取itemView的position
            position = layoutManager!!.getPosition(it)
        }

        onPageChangeListener?.let {
            //newState == RecyclerView.SCROLL_STATE_IDLE 当滚动停止时触发防止在滚动过程中不停触发
            it.onScrollStateChanged(recyclerView, newState)
            if (newState == RecyclerView.SCROLL_STATE_IDLE && oldPosition != position) {
                oldPosition = position
                it.onPageSelected(position)
            }
        }
    }

    interface OnPageChangeListener {

        fun onScrollStateChanged(recyclerView: RecyclerView?, newState: Int)

        fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int)

        fun onPageSelected(position: Int)
    }
}